
const request = (url, method, data, config = {
  //规定一个默认的inAuth，来判断页面是否需要传入token
  isAuth: false
}) => {
  const baseURL = 'http://sx.gaowa.love/'
  //新建一个空head，如果需要将token传入，若不需要则不传，是否需要通过下方判断
  let header = {
  }
  let tokenstr = uni.getStorageSync('token')
  if (config && config.isAuth && tokenstr) {
    header['Authorization'] = tokenstr
  }
  return new Promise((resolve, reject) => {
    uni.request({
      url: baseURL + url,
      method,
      data,
      header: header,
      success: (res) => {
        if (res.statusCode >= 400) {
          uni.showToast({
            title: '网络错误',
            icon: 'none'
          })
          return reject(res)
        }

        if (res.statusCode === 403) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          })
          uni.navigateTo({
            url: '/pages/login/login'
          })
          return reject(res)
        }
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

export default {
  get(url, data, config) {
    return request(url, 'GET', data, config)
  },
  post(url, data, config) {
    return request(url, 'POST', data, config)
  },
  put(url, data, header) {
    return request(url, 'PUT', data, config)
  },
  delete(url, data, config) {
    return request(url, 'DELETE', data, config)
  },
  request
}
